package com.raising.modules.task;

import com.google.common.collect.Lists;
import com.raising.framework.service.BaseService;
import com.raising.framework.spring.SpringUtils;
import com.raising.modules.sys.entity.Olog;
import com.raising.modules.sys.service.OlogService;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 日志记录任务【操作日志】
 * @author gaoy
 */
public class TaskOlog extends BaseService {

	private volatile static TaskOlog singleton;

	public TaskOlog() {
	}

	/**
	 * 获取日志单例
	 * @return
	 */
	public static TaskOlog getSingleton() {
		if (singleton == null) {
			synchronized (TaskOlog.class) {
				if (singleton == null) {
					singleton = new TaskOlog();
				}
			}
		}
		return singleton;
	}

	/**
	 * 日志记录队列
	 */
	private static BlockingQueue<Olog> queueLog = new ArrayBlockingQueue<Olog>(
			100);
	/**日志服务*/
	private static OlogService logService = SpringUtils.getBean(OlogService.class);

	/**
	 * 添加记录
	 * @param log
	 */
	public void add(Olog log) {
		if(null == log.getId() || "".equals(log.getId())){
			log.setId(this.nextId());
		}
		queueLog.offer(log);
		logger.info("记录了一条【操作日志】：" + log.getContent());
	}

	/**
	 * 将日志入库任务
	 */
	public void run() {
		if (queueLog.size() > 0) {
			logger.info("当前【操作日志】队列总数：" + queueLog.size());
		}
		int i = 0;
		// 临时日志堆栈
		List<Olog> logs = Lists.newArrayList();
		while (queueLog.size() > 0) {
			if (i > 100) {
				break;
			}
			Olog log = queueLog.poll();
			logs.add(log);
			i++;
		}
		if (logs.size() > 0) {
			logService.saveBatch(logs);
			logger.info("当前【操作日志】入库队列数：" + logs.size());
		}

	}
}
